package com.fanfan.shiroadmin.modules.sys.service.impl;

import com.fanfan.shiroadmin.common.exception.ServiceRuntimeException;
import com.fanfan.shiroadmin.common.utils.RedisKeysUtil;
import com.fanfan.shiroadmin.common.utils.RedisUtil;
import com.fanfan.shiroadmin.modules.sys.constant.SysConstant;
import com.fanfan.shiroadmin.modules.sys.entity.SysMenuEntity;
import com.fanfan.shiroadmin.modules.sys.entity.SysUserEntity;
import com.fanfan.shiroadmin.modules.sys.service.ISysMenuService;
import com.fanfan.shiroadmin.modules.sys.service.ISysRsService;
import com.fanfan.shiroadmin.modules.sys.service.ISysUserService;
import com.fanfan.shiroadmin.modules.sys.service.ShiroCacheService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author DunFan.Liao
 * @date 2022/1/2 14:46
 */
@Service(ShiroCacheService.BEAN_ID)
@Log4j2
public class ShiroCacheServiceImpl implements ShiroCacheService
{


    @Resource(name = ISysMenuService.BEAN_ID)
    private ISysMenuService sysMenuService;

    @Resource(name = ISysUserService.BEAN_ID)
    private ISysUserService userService;

    @Resource(name = ISysRsService.BEAN_ID)
    private ISysRsService sysRsService;
    @Autowired
    private RedisUtil redisUtil;
    /**
     * sessionNamespace redis用户会话的命名空间
     */
    @Value("${redis.namespace}")
    private String nameSpace;

    @Override
    public void addUserMenuCache(SysUserEntity user) throws ServiceRuntimeException
    {
        List<SysMenuEntity> menuList = new ArrayList<>();
        if (SysConstant.ADMIN_USER_ID.equals(user.getId()))
        {
            // 管理员设置全部权限
            menuList = sysMenuService.queryMenuList();

        }
        else
        {

        }

        // 将用户菜单权限存入缓存
        String redisKey = RedisKeysUtil.getMenuUserKey(nameSpace,user.getUserAcct());
        log.info("用户{}正在进行菜单缓存，缓存key为{}",user.getUserAcct(),redisKey);
        redisUtil.set(redisKey,menuList);
        log.info("用户{}进行菜单缓存结束",user.getUserAcct());
    }

    @Override
    public Set<String> addUserRsUrlCache(SysUserEntity user) throws ServiceRuntimeException
    {
        Set<String> rsUrl = new HashSet<>();

        if (SysConstant.ADMIN_USER_ID.equals(user.getId()))
        {
            // 管理员设置全部权限
            rsUrl = sysRsService.queryRsUrlList();
        }
        else
        {

        }
        // 将用户菜单权限存入缓存
        String redisKey = RedisKeysUtil.getRsUserKey(nameSpace,user.getUserAcct());
        log.info("用户{}正在进行资源路径缓存，缓存key为{}",user.getUserAcct(),redisKey);
        redisUtil.set(redisKey,rsUrl);
        log.info("用户{}进行资源路径缓存结束",user.getUserAcct());
        return rsUrl;
    }
}
